package com.sdkx.wear_os.ui.fragment

import android.annotation.SuppressLint
import android.app.Activity
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.provider.Settings
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.core.net.toFile
import androidx.recyclerview.widget.LinearLayoutManager
import com.sdkx.wear_os.R
import com.sdkx.wear_os.app.MyApplication
import com.sdkx.wear_os.base.BaseFragment
import com.sdkx.wear_os.databinding.FragmentMineBinding
import com.sdkx.wear_os.retrofit.UserInfo
import com.sdkx.wear_os.utils.*
import com.sdkx.wear_os.utils.ToastLogUtils.toastUtil
import com.sdkx.wear_os.viewmodel.AppViewModel
import com.sdkx.wear_os.viewmodel.DownLoadViewModel
import com.sdkx.wear_os.viewmodel.MineViewModel
import kotlinx.coroutines.flow.MutableSharedFlow

/**
 * 我的
 */
class MineFragment : BaseFragment<MineViewModel, FragmentMineBinding>() {

    //全局viewModel
    private val appViewModel by lazy { getAppViewModel<AppViewModel>() }

    //下载
    private val downLoadViewModel: DownLoadViewModel by lazy { getAppViewModel<DownLoadViewModel>() }

    //个人信息
    private var userInfo: UserInfo? = null

    //回值跳转
    private lateinit var startActivityLaunch: ActivityResultLauncher<Intent>
    private var uri: Uri? = null

    //判断当时是否是点击按钮检查更新
    private var isClickUpdate = false

    //标记是否强制
    private var forceReplace = false
    override fun initLayout() = R.layout.fragment_mine

    override fun initView(savedInstanceState: Bundle?) {
        //安装权限跳转回值
        startActivityLaunch =
            registerForActivityResult(ActivityResultContracts.StartActivityForResult()) {
                if (it.resultCode == Activity.RESULT_OK) {
                    //回调是否有权限了
                    uri?.toFile()?.let { installApk(requireActivity(), it) }
                }
                //如果强制更新APP 但还没安装权限 就销毁
                if (forceReplace) {
                    requireActivity().finish()
                }
            }
        //设置列表
        mDataBinding.mineRecyclerview.run {
            layoutManager = LinearLayoutManager(requireContext())
            adapter = mViewModel.mineAdapter
        }
    }

    @SuppressLint("SetTextI18n")
    override fun lazyLoadData() {
        //如果加载了我的页面 设置Toolbar
        appViewModel.mineFragmentFlow.launchAndCollectInx(lifecycle) {
            if (it) {
                isDarkFont = true
                initToolbar(mDataBinding.mineToolbar)
            }
        }
        //退出登录弹窗监听
        mViewModel.centerDialogFlow = MutableSharedFlow()
        mViewModel.centerDialogFlow?.launchAndCollectInx(lifecycle) {
            mViewModel.logout(requireActivity())
        }
        //个人信息
        mViewModel.userInfoFlow.launchAndCollectInx(lifecycle) {
            userInfo = it
            GlideEngine.createGlideEngine().loadImage(
                requireContext(),
                it.userImage,
                mDataBinding.userAvatarIv,
                R.mipmap.logo
            )
            mDataBinding.usernameTv.text = it.userName
            mDataBinding.mobilePhoneNumberTv.text = it.mobile
        }

        //是否更新
        mViewModel.updateFlow.launchAndCollectInx(lifecycle) {
            if (it.appVersion.isNotEmpty()) {
                val v = getVersionName(MyApplication.application)
                val vData = v.split(".")
                val appVersionData = it.appVersion.split(".")
                //强制版本更新
                if (NumberUtils.toInt(vData[0]) < NumberUtils.toInt(appVersionData[0])) {
                    forceReplace = true
                    downLoadViewModel.updateDialog(
                        requireContext(),
                        it.depiction,
                        it.appUrl,
                        forceReplace
                    )
                    return@launchAndCollectInx
                }
                //强制版本更新
                if (appVersionData.size > 1) {
                    if (NumberUtils.toInt(vData[1]) < NumberUtils.toInt(appVersionData[1])) {
                        forceReplace = true
                        downLoadViewModel.updateDialog(
                            requireContext(),
                            it.depiction,
                            it.appUrl,
                            forceReplace
                        )
                        return@launchAndCollectInx
                    }
                }
                //可忽略的更新
                if (appVersionData.size > 2) {
                    if (NumberUtils.toInt(vData[2]) < NumberUtils.toInt(appVersionData[2])) {
                        forceReplace = false
                        downLoadViewModel.updateDialog(
                            requireContext(),
                            it.depiction,
                            it.appUrl,
                            forceReplace
                        )
                        return@launchAndCollectInx
                    }
                }
                if (isClickUpdate)
                    toastUtil("已是最新版本")
            }
        }
        //下载APK监听
        downLoadViewModel.downloadSuccessFlow = MutableSharedFlow()
        downLoadViewModel.downloadSuccessFlow?.launchAndCollectInx(lifecycle) {
            if (it == null) {
                toastUtil("下载失败")
                if (forceReplace) {
                    requireActivity().finish()
                }
                return@launchAndCollectInx
            }
            uri = it
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
                if (!MyApplication.application.packageManager.canRequestPackageInstalls()) {
                    //去打开权限
                    val packageURI = Uri.parse("package:" + getPackageName(requireContext()))
                    val intent = Intent(Settings.ACTION_MANAGE_UNKNOWN_APP_SOURCES, packageURI)
                    startActivityLaunch.launch(intent)
                } else {
                    installApk(requireActivity(), it.toFile())
                    if (forceReplace) {
                        requireActivity().finish()
                    }
                }
            } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                installApk(requireActivity(), it.toFile())
                if (forceReplace) {
                    requireActivity().finish()
                }
            } else {
                installApk2(requireActivity(), it.toFile())
                if (forceReplace) {
                    requireActivity().finish()
                }
            }
        }
        mViewModel.getAndroidRvVersion()
        mViewModel.getLoginUserInfo(requireActivity())
    }

    override fun initListener() {
        super.initListener()
        //退出登录
        mDataBinding.signOutTv.setOnClickListener {
            mViewModel.centerDialog(requireContext(), "退出登录", "确定退出登录吗?").show()
        }
        //列表点击
        mViewModel.mineAdapter.itemClickNoRepeat { view, position ->
            when (position) {
                0 -> {}
                2 -> {
                    //更新
                    isClickUpdate = true
                    mViewModel.getAndroidRvVersion()
                }
                else -> {}
            }
        }
    }
}